package yesjava.news.other;

import org.apache.commons.fileupload.FileItem;
import yesjava.news.utils.ServletUploadUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;

@WebServlet("/upload")
public class FileUploadServlet extends HttpServlet {
    String uploadPath = "D://myfile1/";

    //    myFile  remark
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            String[] remark  =  ServletUploadUtil.getParameterValues("remark",request);
            String[] xingqu  =  ServletUploadUtil.getParameterValues("xingqu",request);
            System.out.println("remark: "+List.of(remark));
            System.out.println("xingqu: "+List.of(xingqu));
            System.out.println("===============================================");
            FileItem[] items = ServletUploadUtil.getParameterFileItemVaues("myFile",request);
            for (FileItem item : items) {
                String fileName = item.getName();//TTT.txt
                String fileName4Save = (int) (Math.random() * 1000000) + (fileName.substring(fileName.lastIndexOf(".")));
                File file2Save = new File(uploadPath, fileName4Save);
                item.write(file2Save);
            }
            //成功后重定向到 提示页面
            response.sendRedirect(request.getContextPath()+"/success.jsp");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }
}
